/**
 * Created by fenglishi on 16/7/21.
 */
function Future() {
    var successValue;
    var errorValue;
    var resolved;
    var rejected;
    this.success = function (resolve) {
        resolved = resolve;
        if(successValue){
            var value = successValue;
            successValue = undefined;
            resolved(value);
        }
        return this;
    };
    this.error = function (reject) {
        rejected = reject;
        if(errorValue){
            var value = errorValue;
            errorValue = undefined;
            rejected(value);
        }
        return this;
    };
    this.resolve = function (value) {
        if(resolved){
            resolved(value);
        }else{
            successValue = {param:value};
        }
    };
    this.reject = function (value) {
        if(rejected){
            rejected(value);
        }else{
            errorValue = {param:value};
        }
    }
    
}
$(function () {
    //
    var uploadUrl = "";
    $().click(function () {
        
    });
    function domCountLessThanNumber($dom,number) {
        var future = new Future();
        if($dom.length < number){
            future.resolve();
        }else{
            future.reject();
        }
        return future;
    }
    //营业执照内容更改
    $("input[name=yyzz]").on("change",function (e) {
        var file = this.files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            var url = e.target.result;
            var $template = $($("#template").html());
            $template.addClass("yyzz-img");
            
            $template.find(">img").prop("src",url);
            $template.find(".del-btn").click(function (e) {
                $(this).closest(".yyzz-img").remove();
                domCountLessThanNumber($(".yyzz-img"),2).success(function () {
                    $("#yyzz-btn").show();
                });
            });
            $("#yyzz-btn").before($template);
            //
            domCountLessThanNumber($(".yyzz-img"),2).error(function () {
                $("#yyzz-btn").hide();
            });
        };
        reader.readAsDataURL(file);
    });
    //店铺门头照
    $("input[name=dpmtz]").on("change",function (e) {
        var file = this.files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            var url = e.target.result;
            var $template = $($("#template").html());
            $template.addClass("dpmtz-img");
            $template.find(">img").prop("src",url);
            $template.find(".del-btn").click(function (e) {
                $(this).closest(".dpmtz-img").remove();
                domCountLessThanNumber($(".dpmtz-img"),1).success(function () {
                    $("#dpmtz-btn").show();
                });
            });
            $("#dpmtz-btn").before($template);
            //
            domCountLessThanNumber($(".dpmtz-img"),1).error(function () {
                $("#dpmtz-btn").hide();
            });
        };
        reader.readAsDataURL(file);
    });
    //店铺环境照
    $("input[name=dphjz]").on("change",function (e) {
        var file = this.files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            var url = e.target.result;
            var $template = $($("#template").html());
            $template.addClass("dphjz-img");
            $template.find(">img").prop("src",url);
            $template.find(".del-btn").click(function (e) {
                $(this).closest(".dphjz-img").remove();
                domCountLessThanNumber($(".dphjz-img"),3).success(function () {
                    $("#dphjz-btn").show();
                });
            });
            $("#dphjz-btn").before($template);
            //
            domCountLessThanNumber($(".dphjz-img"),3).error(function () {
                $("#dphjz-btn").hide();
            });
        };
        reader.readAsDataURL(file);
    });
    //营业执照添加按钮
    $("#yyzz-btn").click(function (e) {
        $("input[name=yyzz]").trigger("click");
    });
    //店铺门头照添加按钮
    $("#dpmtz-btn").click(function (e) {
        $("input[name=dpmtz]").trigger("click");
    });
    //店铺环境照添加按钮
    $("#dphjz-btn").click(function (e) {
        $("input[name=dphjz]").trigger("click");
    });
    //提交
    $("#confirm").click(function (e) {
        //表单校验
        if(!$.trim($("#storeName").val())){
            alert("店铺名不能为空");
            return;
        }
        if(!$.trim($("#storeAddr").val())){
            alert("店铺地址不能为空");
            return;
        }
        if(!$.trim($("#storeTel").val())){
            alert("店铺电话不能为空");
            return;
        }else{
            var phoneNumber = $.trim($("#storeTel").val());
            if(!(/\d+/.test(phoneNumber))){
                alert("电话必须为数字");
                return;
            }
        }
        if(!$.trim($("#storeContact").val())){
            alert("店铺联系人不能为空");
            return;
        }
        if(!$.trim($("#storeCutterCounter").val())){
            alert("美发师数量不能为空");
            return;
        }else{
            var count = $.trim($("#storeCutterCounter").val());
            if(!(/\d+/.test(count))){
                alert("美发师数量必须为数字");
                return;
            }
        }
        //
        if(2 != $(".yyzz-img").length){
            alert("营业执照必须传2张图片");
            return;
        }
        if(1 != $(".dpmtz-img").length){
            alert("未上传店铺门头照");
            return;
        }
        if(3 != $(".dphjz-img").length){
            alert("店铺环境照必须传3张");
            return;
        }
        //
        var formData = new FormData();
        formData.append("storeName",$("#storeName").val());
        formData.append("storeAddr",$("#storeAddr").val());
        formData.append("storeTel",$("#storeTel").val());
        formData.append("storeContact",$("#storeContact").val());
        formData.append("storeCutterCounter",$("#storeCutterCounter").val());
        //
        $(".yyzz-img").each(function (index,elem) {
            var url = $(elem).find("img").prop("src");
            var imgInfoArray = url.split(',');
            var data = imgInfoArray[1];
            var regex = /data:(\w+\/(\w+));base64/;
            var result  = regex.exec(imgInfoArray[0]);//"data:image/png;base64"
            var type = result[1];
            var subffix = result[2];
            data=window.atob(data);
            var ia = new Uint8Array(data.length);
            for (var i = 0; i < data.length; i++) {
                ia[i] = data.charCodeAt(i);
            }
            var blob=new Blob([ia], {type:type});
            formData.append('yyzz_'+index,blob,"yyzz"+index+"."+subffix);
        });
        //
        $(".dpmtz-img").each(function (index,elem) {
            var url = $(elem).find("img").prop("src");
            var imgInfoArray = url.split(',');
            var data = imgInfoArray[1];
            var regex = /data:(\w+\/(\w+));base64/;
            var result  = regex.exec(imgInfoArray[0]);//"data:image/png;base64"
            var type = result[1];
            var subffix = result[2];
            data=window.atob(data);
            var ia = new Uint8Array(data.length);
            for (var i = 0; i < data.length; i++) {
                ia[i] = data.charCodeAt(i);
            }
            var blob=new Blob([ia], {type:type});
            formData.append('dpmtz_'+index,blob,"dpmtz"+index+"."+subffix);
        });
        //
        $(".dphjz-img").each(function (index,elem) {
            var url = $(elem).find("img").prop("src");
            var imgInfoArray = url.split(',');
            var data = imgInfoArray[1];
            var regex = /data:(\w+\/(\w+));base64/;
            var result  = regex.exec(imgInfoArray[0]);//"data:image/png;base64"
            var type = result[1];
            var subffix = result[2];
            data=window.atob(data);
            var ia = new Uint8Array(data.length);
            for (var i = 0; i < data.length; i++) {
                ia[i] = data.charCodeAt(i);
            }
            var blob=new Blob([ia], {type:type});
            formData.append('dphjz_'+ index,blob,"dphjz"+index+"."+subffix);
        });
        ///
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if(xhr.readyState == 4 && xhr.status == 200){
                var b = xhr.responseText;
                console.log(b);
                var ret = JSON.parse(b);

                if(ret['code'] != 0)
                {
                //    qiao.bs.msg({msg:ret['msg'],type:'danger'});
                }
                else
                {
                   //    qiao.bs.msg({msg:ret['msg'],type:'success'});
                   // history.replaceState(null, "", ret['url']);
                    window.location.href = ret['url'];

                }
            }
        };
        xhr.open('POST', uploadUrl, true);
        xhr.send(formData);
    });
});



